package egovframework.npqs.pqi.mobile.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsonparser.RelationDiseasePestThread;
import egovframework.npqs.pqi.mobile.jsonparser.RelationDiseasePestThread.RelationDiseasePestThreadCallback;

//수입금지, 긴급제한, 관련병해충
public class RelationDiseasePestActivity extends Activity implements 
	RelationDiseasePestThreadCallback{
	private TextView titleTxt, navigation;	// 상단 타이틀
	private AppStatus myapp;
	private Context context;
	private ListView listView;
	private RelationListAdapter relationAdapter;
	private UrgencyAdapter urgencyAdapter;
	private RelationDiseasePestThread relationThread;
	private String value, natCd, offCd, recNo;
	private TextView text2_1, text3_1, text4_1, text5_1;
	private RelativeLayout layout04, layout05;
	private ImageButton btnHome, btn_exit;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private String type;
	
	//new 호출 결과값 저장
    private String mResult;
    
	/* G-MOBILE 변수*/
    private String temp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_relation_disease_pest);
		
		/*로그, 코드, - */
		Intent intent = getIntent();
		value = intent.getStringExtra("value").trim();
		natCd = intent.getStringExtra("natCd");
		offCd = intent.getStringExtra("offCd");
		recNo = intent.getStringExtra("recNo");
		
		if(value.toString().equals("1")){
			AppStatus.navigation.addPathLocation("긴급제한");
		}else if(value.toString().equals("2")){
			AppStatus.navigation.addPathLocation("수입금지");
		}else{
			AppStatus.navigation.addPathLocation("관련병해충정보");
		}
		
		Log.i("params info", "params info value : "+value+", natCd : "+natCd+", offCd : "+offCd+", recNo : "+recNo);
		
		init();
		
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) context.getApplicationContext();
		myapp.startBroker(context);
		
		listView = (ListView)findViewById(R.id.relation_list);
		
		relationAdapter = new RelationListAdapter();
		urgencyAdapter = new UrgencyAdapter();
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		
		if(value.toString().equals("1")){
			titleTxt.setText("긴급제한");
		}else if(value.toString().equals("2")){
			titleTxt.setText("수입금지");
		}else{
			titleTxt.setText("관련병해충정보");
		}
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		dateLoad();
	}
	
	private void dateLoad(){
		
		if(value.equals("1")){
			//긴급제한
			type = "020";
		}else if(value.equals("2")){
			//수입금지
			type = "010";
		}else{
			//관련병해충
			type = "000";
		}
		
		Log.i("type", "type : "+type);
		
		myapp.showDialogNo(context);
		temp = "처음검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
	}
	
	public void threadStart(){
		if("처음검색".equals(temp)){
    		relationThread = new RelationDiseasePestThread(context, this, type, natCd, offCd, recNo, value, AppStatus.getmUserId());
    		relationThread.start();
    	}
	}
	
	//관련병해충을 담는 아답터
	class RelationListAdapter extends BaseAdapter {
		TextView natNm, resDe, prdlstNm, botNm, viewDamDegNm;

		@Override
		public int getCount() {
			return myapp.getArrRelationDeiseasePastItem().size();
		}

		@Override
		public Object getItem(int position) {
			return myapp.getArrRelationDeiseasePastItem().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_relation_disease_item, parent, false);
    		}
			
			layout04 = (RelativeLayout)convertView.findViewById(R.id.layout04);
			text2_1 = (TextView)convertView.findViewById(R.id.text_2_1);
			text3_1 = (TextView)convertView.findViewById(R.id.text_3_1);
			text4_1 = (TextView)convertView.findViewById(R.id.text_4_1);
			
			if(value.equals("3")){
				layout04.setVisibility(View.VISIBLE);
				text2_1.setText("국가명");
				text3_1.setText("학명");
				text4_1.setText("발견상세");
			}
			
			prdlstNm = (TextView)convertView.findViewById(R.id.content_1_1);
			natNm = (TextView)convertView.findViewById(R.id.content_2_1);
			resDe = (TextView)convertView.findViewById(R.id.content_2_2);
			botNm = (TextView)convertView.findViewById(R.id.content_3_1);
			viewDamDegNm = (TextView)convertView.findViewById(R.id.content_4_1);
			
			prdlstNm.setText(myapp.getArrRelationDeiseasePastItem().get(position).getPrdlstNm());
			natNm.setText(myapp.getArrRelationDeiseasePastItem().get(position).getNatNm());
			resDe.setText(myapp.getArrRelationDeiseasePastItem().get(position).getResDe());
			botNm.setText(myapp.getArrRelationDeiseasePastItem().get(position).getBotNm());
			viewDamDegNm.setText(myapp.getArrRelationDeiseasePastItem().get(position).getViewDamDegNm());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			
		}
	}
	
	//긴급제한, 수입금지를 담는 아답터
	class UrgencyAdapter extends BaseAdapter {
		TextView natNm, prdlstNm, natDetArear, prbCau, prbDate, cmmnPrdlstNm;

		@Override
		public int getCount() {
			return myapp.getArrUrgencyLimitItem().size();
		}

		@Override
		public Object getItem(int position) {
			return myapp.getArrUrgencyLimitItem().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_relation_disease_item, parent, false);
    		}
			
			//일단 하드코딩
			layout04 = (RelativeLayout)convertView.findViewById(R.id.layout04);
			layout05 = (RelativeLayout)convertView.findViewById(R.id.layout05);
			
			text2_1 = (TextView)convertView.findViewById(R.id.text_2_1);
			text3_1 = (TextView)convertView.findViewById(R.id.text_3_1);
			text4_1 = (TextView)convertView.findViewById(R.id.text_4_1);
			text5_1 = (TextView)convertView.findViewById(R.id.text_5_1);
			
			text2_1.setText("국가명");
			
			if(value.equals("1")){
				//긴급제한
				text3_1.setText("국가상세지역");
				layout04.setVisibility(View.VISIBLE);
				layout05.setVisibility(View.VISIBLE);
				text4_1.setText("근거사유");
				text5_1.setText("금지기간");
			}else {
				//수입금지
				text3_1.setText("국가상세지역");
			}
			
			prdlstNm = (TextView)convertView.findViewById(R.id.content_1_1);
			natNm = (TextView)convertView.findViewById(R.id.content_2_1);
			natDetArear = (TextView)convertView.findViewById(R.id.content_2_2);
			prbCau = (TextView)convertView.findViewById(R.id.content_3_1);
			prbDate = (TextView)convertView.findViewById(R.id.content_4_1);
			
			prdlstNm.setText(myapp.getArrUrgencyLimitItem().get(position).getPrdlstNm());
			natNm.setText(myapp.getArrUrgencyLimitItem().get(position).getNatNm());
			natDetArear.setText(myapp.getArrUrgencyLimitItem().get(position).getNatDetArear());
			prbCau.setText(myapp.getArrUrgencyLimitItem().get(position).getPrbCau());
			prbDate.setText(myapp.getArrUrgencyLimitItem().get(position).getPrbDate());
			
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			
		}
	}

	@Override
	public void OnRelationDiseasePestCompleted(boolean isNetworkConntected,
			boolean results, String message) {
		
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(results) {
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				if(value.equals("3")){
					relationAdapter.notifyDataSetChanged();
					listView.setAdapter(relationAdapter);
				}else{
					urgencyAdapter.notifyDataSetChanged();
					listView.setAdapter(urgencyAdapter);
				}
				
				break;

			case MSG_QUARANTINE_ERROR:
				
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				Log.i("관련병해충 data3 ", errMsg);
				/*
				if(value=="1"){
					relationAdapter.notifyDataSetChanged();
					listView.setAdapter(relationAdapter);
				}else{
					Log.i("value", "value : "+value);
					urgencyAdapter.notifyDataSetChanged();
					listView.setAdapter(urgencyAdapter);
				}*/
				new AlertDialog.Builder(RelationDiseasePestActivity.this)
				.setTitle("실패")
				.setMessage(errMsg)
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							finish();
						} catch (Exception e) {

						}
					}
				})
				.setCancelable(false)
				.show();
				
				//myapp.utilm.ShowDialog(RelationDiseasePestActivity.this, "실패", errMsg, 20);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(RelationDiseasePestActivity.this, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	@Override
	public void OnRelationDiseasePestError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		Log.i("관련병해충 data2 ", errorItem.getrDesc());
		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
	//new 토스트 창
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
}